<template>
  <div class="project-management">
    <!-- 文件上传组件 -->
    <el-card class="upload-section" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>上传项目文件</h2>
        </div>
      </template>
      <div class="upload-content">
        <FileUpload @upload-complete="handleUploadComplete" />
        <el-button
          type="primary"
          class="local-deploy-btn"
          @click="handleLocalDeploy"
        >
          <el-icon class="el-icon--left"><Folder /></el-icon>
          本地文件入库
        </el-button>
      </div>
    </el-card>

    <!-- 项目列表 -->
    <el-card class="project-list" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>项目列表</h2>
        </div>
      </template>
      <div class="project-list-content">
        <div class="table_operate">
          <div class="search_form">
            <el-input
              v-model="searchFileName"
              placeholder="请输入文件名"
              clearable
              @clear="handleClearSearchFileName"
            >
              <template #append>
                <el-button
                  :icon="Search"
                  @click="handleSearchFileName"
                /> </template
            ></el-input>
            <el-select
              v-model="searchUploadStatus"
              placeholder="请选择状态"
              clearable
              @change="changeUploadStatus"
            >
              <el-option label="已完成" value="completed" />
              <el-option label="进行中" value="uploading" />
              <el-option label="失败" value="failed" />
            </el-select>
            <el-select
              v-model="searchExtractStatus"
              placeholder="请选择部署状态"
              clearable
              @change="changeExtractStatus"
            >
              <el-option label="未部署" value="pending" />
              <el-option label="部署中" value="extracting" />
              <el-option label="已部署" value="completed" />
              <el-option label="已删除" value="deleted" />
            </el-select>
          </div>
          <div class="operate_btns">
            <el-button type="primary" @click="handleExtractBatch"
              >批量部署</el-button
            >
            <el-button type="danger" @click="handleDeleteFile">
              批量删除
            </el-button>
          </div>
        </div>

        <div class="table-container">
          <!-- 项目表格 -->
          <el-table
            :data="projectList"
            style="width: 100%"
            v-loading="loading"
            row-key="_id"
            @selection-change="handleSelectionChange"
            height="calc(100vh - 400px)"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="originalName" label="文件名" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{
                  getStatusText(row.status)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="extractStatus" label="部署状态">
              <template #default="{ row }">
                <el-tag :type="getExtractStatusType(row.extractStatus)">{{
                  getExtractStatusText(row.extractStatus)
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="上传时间">
              <template #default="{ row }">
                {{ new Date(row.createdAt).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button
                  v-if="
                    row.status === 'completed' &&
                    (!row.extractStatus ||
                      row.extractStatus === 'pending' ||
                      row.extractStatus === 'failed' ||
                      row.extractStatus === 'deleted')
                  "
                  size="small"
                  type="primary"
                  @click="handleExtract(row)"
                  >部署</el-button
                >
                <el-button
                  v-if="row.extractStatus === 'completed'"
                  size="small"
                  type="danger"
                  @click="handleDeleteExtracted(row)"
                  >删除部署文件</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 本地文件列表弹窗 -->
    <LocalFileDialog
      v-model:visible="localFileDialogVisible"
      :fileList="localFileList"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import FileUpload from "./upload/index.vue";
import LocalFileDialog from "./localFile/index.vue";
import {
  getUeProjects,
  extractAction,
  deleteExtractAction,
  deleteFileAction,
  getLocalFiles,
} from "@/api/modules/ueProject";
import { ElMessage, ElNotification, ElMessageBox } from "element-plus";
import { useWebSocket } from "@/hooks/socketClient";
import { Search, Folder } from "@element-plus/icons-vue";
const { connected, onMessage, disconnect } = useWebSocket(
  "ueProject",
  import.meta.env.VITE_API_BASE_WS_URL
);

// 监听WebSocket消息
onMessage("merge_completed", (data) => {
  console.log(data);
  ElNotification.success({
    title: "上传通知:",
    message: `${data.originalName} 已成功上传`,
  });
  fetchProjects();
});

onMessage("extract_completed", (data) => {
  ElNotification.success({
    title: "部署通知:",
    message: `${data.fileName} 已成功部署`,
  });
  fetchProjects();
});
onMessage("extract_error", (data) => {
  ElNotification.error({
    title: "部署通知:",
    message: `${data.error} 部署失败`,
  });
  fetchProjects();
});

onMessage("delete_completed", (data) => {
  ElNotification.success({
    title: "删除通知:",
    message: `${data.fileName} 已成功删除`,
  });
  fetchProjects();
});
onMessage("delete_all_completed", (data) => {
  ElNotification.success({
    title: "删除通知:",
    message: `${data.fileName} 及原始文件已成功删除`,
  });
  fetchProjects();
});
onMessage("deploy_completed", (data) => {
  ElNotification.success({
    title: "入库通知:",
    message: `${data.fileName}入库成功！`,
  });
  getLocalFileData();
  fetchProjects();
});

onMessage("local_file_delete_completed", (data) => {
  ElNotification.success({
    title: "删除通知:",
    message: `${data.fileName} 已成功删除`,
  });
  getLocalFileData();
});

// 搜索表单
const searchFileName = ref("");
const searchUploadStatus = ref("");
const searchExtractStatus = ref("");
const handleSearchFileName = () => {
  fetchProjects();
};
const handleClearSearchFileName = () => {
  searchFileName.value = "";
  fetchProjects();
};
const changeUploadStatus = (val) => {
  if (!val) {
    searchUploadStatus.value = "";
  }
  fetchProjects();
};
const changeExtractStatus = (val) => {
  if (!val) {
    searchExtractStatus.value = "";
  }
  fetchProjects();
};

const selectIds = ref([]);
const handleSelectionChange = (val) => {
  selectIds.value = val.map((item) => item._id);
};
// 表格数据
const projectList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取项目列表
const fetchProjects = async () => {
  loading.value = true;
  try {
    const res = await getUeProjects({
      page: currentPage.value,
      pageSize: pageSize.value,
      originalName: searchFileName.value,
      status: searchUploadStatus.value,
      extractStatus: searchExtractStatus.value,
    });
    projectList.value = res.data;
    total.value = res.pagination.total;
  } catch (error) {
    ElMessage.error("获取项目列表失败");
  } finally {
    loading.value = false;
  }
};

// 状态显示
const getStatusType = (status) => {
  const types = {
    completed: "success",
    pending: "warning",
    failed: "danger",
    deleting: "info",
  };
  return types[status] || "info";
};

const getStatusText = (status) => {
  const texts = {
    completed: "已完成",
    pending: "上传中",
    failed: "失败",
    deleting: "删除中",
  };
  return texts[status] || status;
};

const getExtractStatusType = (status) => {
  const types = {
    pending: "info",
    extracting: "warning",
    completed: "success",
    failed: "danger",
    deleted: "danger",
    deleting: "info",
  };
  return types[status] || "info";
};

const getExtractStatusText = (status) => {
  const texts = {
    pending: "未部署",
    extracting: "部署中",
    completed: "已部署",
    failed: "部署失败",
    deleted: "已删除",
    deleting: "删除中",
  };
  return texts[status] || status;
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchProjects();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchProjects();
};

// 文件操作
const handleExtract = async (row) => {
  // TODO: 实现解压功能
  ElMessage.success(`开始部署文件: ${row.originalName}`);
  try {
    extractAction({ ids: [row._id] }).then((res) => {
      console.log(res);
      fetchProjects(); // 刷新项目列表
    });
  } catch (error) {
    ElMessage.error("部署异常！");
  }
};

// 本地文件列表弹窗
const localFileDialogVisible = ref(false);
const localFileList = ref([]);
const getLocalFileData = () => {
  getLocalFiles()
    .then((res) => {
      localFileList.value = res.data;
    })
    .catch(() => {
      ElMessage.error("获取本地文件列表失败");
    });
};
const handleLocalDeploy = () => {
  getLocalFileData();
  localFileDialogVisible.value = true;
};
const handleExtractBatch = async () => {
  if (selectIds.value.length === 0) {
    ElMessage.warning("请先选择需要部署的项目");
    return;
  }

  ElMessage.success(`开始批量部署文件`);
  try {
    const res = await extractAction({ ids: selectIds.value });
    console.log(res);
    fetchProjects(); // 刷新项目列表
  } catch (error) {
    ElMessage.error("批量部署异常！");
  }
};

const handleDeleteExtracted = async (row) => {
  // 添加确认弹窗
  ElMessageBox.confirm(
    `确定要删除部署文件: ${row.originalName} 吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      // ElMessage.success(`删除部署文件: ${row.originalName}`);
      try {
        const res = await deleteExtractAction({ id: row._id });
        if (res.success) {
          fetchProjects(); // 刷新项目列表
        } else {
          ElMessage.warning(`请先停止关联${res.fileName} 文件的UE进程`);
        }
      } catch (error) {
        ElMessage.error("删除异常！");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
const handleDeleteFile = async () => {
  if (selectIds.value.length === 0) {
    ElMessage.warning("请先选择需要删除的项目");
    return;
  }
  // 添加确认弹窗
  ElMessageBox.confirm(
    `此操作将删除选中项部署文件及其原始文件，是否继续？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      ElMessage.info(`开始批量删除文件`);
      try {
        const res = await deleteFileAction({ ids: selectIds.value });
        res.forEach(item => {
          if (item.success) {
            ElMessage.success(`删除文件: ${item.fileName} 成功`);
          } else {
            ElMessage.warning(`请先停止关联${item.fileName} 文件的UE进程`);
          }
        });
        fetchProjects(); // 刷新项目列表
      } catch (error) {
        ElMessage.error("删除异常！");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
// 处理上传完成事件
const handleUploadComplete = () => {
  fetchProjects();
};

onMounted(() => {
  fetchProjects();
});
</script>

<style scoped>
.project-management {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.upload-section {
  margin-bottom: 0;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  :deep(.el-card__header) {
    padding: 12px 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .card-header {
    h2 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }
  }

  .upload-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
    align-items: center;
    padding: 20px;
  }

  .local-deploy-btn {
    width: 100%;
    max-width: 320px;
  }
}

.project-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  :deep(.el-card__header) {
    padding: 12px 20px;
    border-bottom: 1px solid #ebeef5;
  }

  .card-header {
    h2 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }
  }

  .project-list-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding: 20px;
  }
}

.table_operate {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
  min-width: 0;
}

.operate_btns {
  display: flex;
  gap: 16px;
  margin-left: auto;
  flex-wrap: nowrap;
  min-width: 200px;
}

.search_form {
  display: flex;
  gap: 16px;
  flex: 1;
  min-width: 0;

  :deep(.el-input) {
    flex: 2;
    min-width: 200px;
  }

  :deep(.el-select) {
    flex: 1;
    min-width: 120px;
  }
}

@media screen and (max-width: 1200px) {
  .table_operate {
    flex-direction: column;
    align-items: stretch;
  }

  .operate_btns {
    margin-left: 0;
    justify-content: flex-start;
  }

  .search_form {
    flex-direction: row;
  }
}

@media screen and (max-width: 768px) {
  .search_form {
    flex-wrap: wrap;

    :deep(.el-input),
    :deep(.el-select) {
      flex: 1 1 100%;
      width: 100%;
    }
  }

  .operate_btns {
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;

    .el-button {
      width: 100%;
      margin-left: 0;
    }
  }
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
